<template>
    <div id="subLine-controller">
      <div class="title-bg"><i class="iconfont metro-lineRoute"></i> 地铁线路</div>
      <div class="item-wrapper">
        <div
          class="item"
          v-for="(item, index) in subwayRoutes"
          :key="index"
          @click="changeLine(index, item)">
          <div
            class="box"
            :style="{
              borderColor: item.color,
              backgroundColor: item.choosed ? item.color : 'rgba(0,0,0,0)',
            }"></div>
          <span :style="{ color: '#34c5cf' }">{{ item.name.slice(-3) }}</span>
        </div>
      </div>
    </div>
    <div class="active-panel">
      <div class="header">
        <strong><i class="iconfont icon-course"></i>发展历程</strong>
        <div class="controler">
          <i class="iconfont metro-pause" @click="pause()"></i>
          <i class="iconfont metro-play" @click="play()"></i>
          <i class="iconfont metro-icon-replay-copy" @click="replay()"></i>
        </div>
      </div>
      <div class="content">
        <a-slider
          style="width: 500px; color: #fff"
          v-model:value="currentTime"
          :marks="scrollline"
          :step="0.01"
          :min="min"
          :max="max"
          :tip-formatter="null">
        </a-slider>
      </div>
      <div class="message">
        {{ message }}
      </div>
    </div>
  </template>
  
  <script setup>
  import * as Cesium from 'cesium'
 
  import { onMounted, ref, watch,onBeforeUnmount,onUnmounted } from 'vue'
  import { useLineData, watchLineData } from '@/store/index'
  import { line_history } from '@/store/staticData.js'
  import { getLine } from '@/api/line'
  import { initViewer } from '@/cesiumTools/sceneManager'
  import { flyToDefaultView } from '@/cesiumTools/sceneManager.js'
  import _ from 'lodash'
  const lineDataStore = useLineData()
  const viewer = lineDataStore.viewer
  const max = ref(1)
  const min = ref(0)
  const checkline = ref(0)
  const subwayRoutes = ref([])
  const lineData = ref([])
  const line = ref([])
  const scrollline = ref({})
  const currentTime = ref(0)
  const message = ref('')
  const historyTime = ref([])
  const isAnimate = ref(false)
  const length = ref(0)
  const resPaths = ref([])
  const curPaths = ref([])
  let positionLine = []
  let lineEntity = null
  let trainEntity = null
  let Cartesian3Line = []

  

  const changeLine = (index, item) => {
    intervalId && cancelAnimationFrame(intervalId)
    // 重置所有线路的选中状态
    subwayRoutes.value.forEach((sub) => {
      sub.choosed = false
    })
    // 选中当前线路
    item.choosed = true
    //先将之前的线路清除
    viewer.entities.remove(lineEntity)
    checkline.value = index
    line.value = lineData.value[checkline.value].paths
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(line.value[180].lng, line.value[180].lat, 90000),
    })
    //将二维数组展开,变成一维数组
    resPaths.value = line.value.flatMap((obj) => [obj.lng, obj.lat])
    scrollline.value = {}
    //选中几号线将在滚动条中显示信息
    const history = line_history[index].history
    history.map((item, index) => {
      const time = index / history.length.toFixed(2)
      scrollline.value[time] = item.timePoint
      min.value = 0
      currentTime.value = 0
      historyTime.value.push({ time: time, word: item.message })
    })
    //拖动进度条,使简介显示相应信息,通过当前时间
    length.value = lineData.value[checkline.value].length
    getPolyline()
    play()
  }
  
  onMounted(async () => {
    // const viewer = initViewer("cesium-viewer");
    lineData.value = await getLine()
    console.log(lineData.value)
  
    const res = _.cloneDeep(lineData.value)
  
    subwayRoutes.value = res.map((item) => {
      return {
        ...item,
        choosed: false,
      }
    })
  
    lineDataStore.controlAll(false)
    flyToDefaultView(viewer)
    //移除之前的列车
    viewer.entities.remove(trainEntity)
    //清除动画
    isAnimate.value = false

  })
  
  //将地铁线路绘制出来
  const getPolyline = () => {
    lineEntity = viewer.entities.add({
      polyline: {
        positions: new Cesium.CallbackProperty(function (time, result) {
          return positionLine
        }, false),
        width: 5,
      },
      material: new Cesium.PolylineGlowMaterialProperty({
        color: Cesium.Color.BLUE,
        glowPower: 1.0,
      }),
      show: true,
    })
    viewer.trackedEntity = lineEntity //将动态轨迹线跟踪
  }
  
  watch(currentTime, (newVal, oldVal) => {
    historyTime.value.map((item, index) => {
      if (newVal >= item.time) {
        message.value = item.word
      }
    })
    renderAnmation()
  })
  //点击按钮使页面暂停
  const pause = () => {
    isAnimate.value = false
  }
  let intervalId = null
  const animate = () => {
    if (isAnimate.value) {
      currentTime.value == 0
      currentTime.value += 0.005
      intervalId = requestAnimationFrame(animate)
      renderAnmation()
    }
  }
  
  const renderAnmation = () => {
    const rate = currentTime.value / max.value
    let index = Math.ceil(rate * resPaths.value.length)
  
    // 我们的坐标两个为一组，不为双数的话，就加一
    if (index % 2 !== 0) {
      index = index + 1
    }
    if (currentTime.value >= 1) {
      isAnimate.value = false
    }
  
    curPaths.value = resPaths.value.slice(0, index)
    //转为笛卡尔坐标
    Cartesian3Line = convertFlatTo2DArray(curPaths.value)
    positionLine = Cartesian3Line.map((item) => Cesium.Cartesian3.fromDegrees(item[0], item[1], 0))
  
    // intervalId = requestAnimationFrame(animate)
  }
  function convertFlatTo2DArray(flatArray) {
    let result = []
    for (let i = 0; i < flatArray.length; i += 2) {
      result.push([flatArray[i], flatArray[i + 1]])
    }
    return result
  }
  
  //点击按钮使滚动条前进,利用currentTime++来实现
  const play = () => {
    // getPolyline()
    isAnimate.value = true
    intervalId = requestAnimationFrame(animate)
    // if (isAnimate.value) {
    //     getPolyline()
    //     intervalId = requestAnimationFrame(animate)
    // } else {
    //     // cancelAnimationFrame(intervalId)
    //     animate()
    // }
    // animate()
  }
  
  const replay = () => {
    currentTime.value = 0
    cancelAnimationFrame(intervalId)
    //先将之前的线路清除
    viewer.entities.remove(positionLine)
    positionLine = null
    play()
  }
  
  onUnmounted(() => {
    cancelAnimationFrame(intervalId)
    viewer.entities.remove(positionLine)
    positionLine = null
    isAnimate.value = false
    lineDataStore.controlAll(true)
  })
  </script>
  
  <style scoped>
  #subLine-controller {
    position: absolute;
    bottom: 8%;
    left: 32.5%;
    transform: translateX(-50%);
    width: 180px;
    height: 200px;
    background-color: rgba(0, 0, 0, 0.3);
    border: 1px solid #ab7818;
    display: flex;
    flex-direction: column;
  }
  
  .title-bg {
    width: 100%;
    height: 30px;
    background: url(/src/assets/uiResources/title-bg.png);
    background-size: contain;
    color: #fff;
    background-repeat: no-repeat;
    line-height: 30px;
    margin-left: 10px;
    background: rgb(255, 255, 255);
    background-image: linear-gradient(180deg, rgba(255, 255, 255, 1) 9%, rgba(211, 156, 50, 1) 57%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }
  
  .box {
    width: 10px;
    height: 10px;
    border-width: 1px;
    border-style: solid;
    background: transparent;
    user-select: all;
    cursor: pointer;
  }
  .item {
    width: 65px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 3px;
    background-color: rgba(255, 255, 255, 0.2);
    border: 1px solid #885f12;
    color: #fff;
    font-size: 10px;
    pointer-events: all;
    cursor: pointer;
  }
  /* .item {
    width: 3.385vw;
    height: 1.042vw;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 3px;
    background-color: rgba(255, 255, 255, 0.2);
    border: 1px solid #885f12;
    color: #fff;
    font-size: 0.521vw;
    pointer-events: all;
    cursor: pointer;
  } */
  
  .item:hover {
    border: 1px solid #d8961a;
  }
  
  .item > span {
    line-height: 0.469vw;
  }
  
  .item > input {
    outline: none;
    border: none;
    transition: all 0.3s ease;
  }
  
  .item-wrapper {
    display: flex;
    justify-content: space-around;
    align-content: space-around;
    flex-wrap: wrap;
    flex: 1;
    padding: 4px;
    overflow: hidden;
  }
  
  .active-panel {
    width: 600px;
    height: 200px;
    border: 1px solid #ab7818;
    background-color: rgba(0, 0, 0, 0.3);
    position: absolute;
    left: 38%;
    bottom: 8%;
    color: #fff;
    display: flex;
    flex-direction: column;
  }
  
  .active-panel > .header {
    height: 1.563vw;
    padding: 0.208vw;
  
    margin-bottom: -0.521vw;
    font-family: '等线Bold';
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .active-panel > .header > strong {
    background: rgb(255, 255, 255);
    background-image: linear-gradient(180deg, rgba(255, 255, 255, 1) 9%, rgba(211, 156, 50, 1) 57%);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }
  
  .controler {
    width: 100px;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
  
  .controler > i {
    cursor: pointer;
    pointer-events: all;
    font-size: 20px;
  }
  
  .controler > i:hover {
    background: rgb(255, 255, 255);
    background-image: linear-gradient(180deg, rgba(255, 255, 255, 1) 9%, rgba(211, 156, 50, 1) 57%);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }
  
  .active-panel > .header > strong {
    font-weight: normal;
    margin-right: 0.521vw;
  }
  
  .active-panel > .header > span {
    font-size: 0.625vw;
  }
  
  .content {
    flex: 1;
    padding: 0 30px;
    margin-top: 30px;
  }
  
  .message {
    position: absolute;
    bottom: 26px;
    left: 50%;
    transform: translateX(-50%);
    background-color: rgba(0, 0, 0, 0.3);
    color: #fff;
    text-align: center;
  }
  
  :deep(.ant-slider-mark-text) {
    color: #fff;
  }
  </style>
  